<?php

namespace App\Console\Commands;

use App\Ant\Jobs\FurnitureTaskJob;
use App\Ant\Jobs\LabelTaskJob;
use App\Ant\Jobs\MaterialTaskJob;
use App\Ant\Jobs\TaskJob;
use App\Models\Company\Task;
use App\Models\LabelTask;
use Carbon\Carbon;
use Illuminate\Console\Command;

class Release extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'release:archive';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Release archive';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $tasks = \App\Models\Company\Task::get();
        $tasks->each(function (Task $task) {
            $now = Carbon::now()->timestamp;
            $start = Carbon::parse($task->time)->timestamp;
            if ($start - $now > 0) {
                TaskJob::dispatch($task)
                    ->onConnection('redis')
                    ->onQueue('releasea')
                    ->delay($start - $now);
            }
        });

        $material = Task\Material::get();
        $material->each(function (Task\Material $material) {
            $now = Carbon::now()->timestamp;
            $start = Carbon::parse($material->time)->timestamp;
            if ($start - $now > 0) {
                MaterialTaskJob::dispatch($material)
                    ->onConnection('redis')
                    ->onQueue('releasea')
                    ->delay($start - $now);
            }
        });

        $labelTask = LabelTask::get();
        $labelTask->each(function (LabelTask $label) {
            $now = Carbon::now()->timestamp;
            $start = Carbon::parse($label->time)->timestamp;
            if ($start - $now > 0) {
                LabelTaskJob::dispatch($label)
                    ->onConnection('redis')
                    ->onQueue('releasea')
                    ->delay($start - $now);
            }
        });

        $furniture = Task\Furniture::get();
        $furniture->each(function (Task\Furniture $furniture) {
            $now = Carbon::now()->timestamp;
            $start = Carbon::parse($furniture->time)->timestamp;
            if ($start - $now > 0) {
                FurnitureTaskJob::dispatch($furniture)
                    ->onConnection('redis')
                    ->onQueue('releasea')
                    ->delay($start - $now);
            }
        });
    }
}
